package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.ArticleMapper;
import com.example.forum.dao.BoardMapper;
import com.example.forum.dao.UserMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import com.example.forum.services.IUserService;
import com.example.forum.utils.StringUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {
    /**
     * 用户和板块以及文章的操作
     */
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private IUserService userService;
    @Resource
    private IBoardService boardService;
    @Override
    public void create(Article article) {
        //非空校验
        if (article == null || article.getUserId() == null || article.getBoarId() == null ||
                StringUtil.isEmpty(article.getContent()) ||
                StringUtil.isEmpty(article.getTitle())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        article.setVisitCount(0);//设置默认访问数
        article.setReplyCount(0);//设置默认回复数
        article.setLikeCount(0);//设置默认点赞数
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        //写入数据库
        int articleRow = articleMapper.insertSelective(article);
        if (articleRow <= 0) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //获取用户信息
        User user = userService.selectById(article.getUserId());
        //没有找到指定的用户信息
        if (user == null) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //更新用户发帖数
        userService.addOneArticleCountById(user.getId());
        //获取板块信息
        Board board = boardService.selectById(article.getBoarId());
        //是否在数据库中有对应的板块
        if (board == null) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //更新板块中帖子的数量
        boardService.addOneArticleCountById(board.getId());
        //打印日志
        log.info(ResultCode.SUCCESS.toString() +
                ",user id=" + article.getUserId() + ",board id=" + article.getBoarId()
                + ",article id=" + article.getId() + "发帖成功");

    }

    @Override
    public List<Article> selectAll() {
        List<Article>articles=articleMapper.selectAll();
        return articles;
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        // 非空校验
        if (boardId == null || boardId <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 校验版块是否存在
        Board board = boardService.selectById(boardId);
        if (board == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString() + ", board id = " + boardId);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        Long boarId=boardId;
        // 调用DAO，查询
        List<Article> articles = articleMapper.selectAllByBoardId(boarId);
        // 返回结果
        return articles;
    }

    /**
     * 根据帖子Id返回帖子详情
     * @param id 帖子Id
     * @return 返回帖子的基本详情
     */
    @Override
    public Article selectById(Long id) {
        //非空校验
        if(id==null||id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article=articleMapper.selectByPrimaryKey(id);
        if(article==null){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        return article;
    }

    /**
     * 根据帖子Id获取帖子信息并且更新帖子的访问次数
     * @param id 帖子ID
     * @return 返回更新后的帖子信息
     */
    @Override
    public Article selectDetailById(Long id) {
        //非空校验
        if(id==null||id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO查看该资源是否存在
        Article article=articleMapper.selectDetailById(id);
        if(article==null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //更新帖子访问次数
        Article updateArticle=new Article();
        updateArticle.setId(id);
        updateArticle.setVisitCount(article.getVisitCount()+1);
        updateArticle.setBoarId(article.getBoarId());
        //保存到数据库
        int row=articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        article.setVisitCount(updateArticle.getVisitCount());
        return article;
    }

    /**
     * 编辑帖子
     * @param id 帖子Id
     * @param title 帖子标题
     * @param content 帖子正文
     */
    @Override
    public void modify(Long id, String title, String content) {
        //非空校验
        if(id==null||id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //判断title和content是否为空
        if(StringUtil.isEmpty(title)||StringUtil.isEmpty(content)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //创建对象将更新后的内容写入数据库
        Article updateArticle=new Article();
        updateArticle.setContent(content);
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setUpdateTime(new Date());
        int row=articleMapper.updateByPrimaryKeySelective(updateArticle);
        //判断是否更新失败
        if(row!=1){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
    }

    /**
     * 根据帖子ID对帖子点赞数做修改
     * @param id 帖子Id 根据帖子ID对帖子的点赞数做修改
     */

    @Override
    public void thumbsUpById(Long id) {
        //参数校验
        if(id==null||id<=0){
            //写日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article=articleMapper.selectByPrimaryKey(id);
        //构造更新对象
        Article updateArticle=new Article();
        updateArticle.setId(id);
        updateArticle.setLikeCount(article.getLikeCount()+1);
        //写入数据库
        int row=articleMapper.updateByPrimaryKeySelective(updateArticle);
        //判断操作是否成功
        if(row!=1){
            log.warn("点赞失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LIKEADD_EXISTS));
        }
        log.info("点赞成功");
    }

    /**
     * 根据帖子ID删除帖子
     * @param id 帖子ID
     */
    @Override
    public void deleteById(Long id) {
        //参数的非空校验
        if(id==null||id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article=articleMapper.selectByPrimaryKey(id);
        //判断ID代表的目标帖子是否存在
        if(article==null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        Article updateArticle=new Article();
        updateArticle.setId(id);
        updateArticle.setDeleteState((byte)1);
        //调用DAO
        int row=articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            //更新失败打印日志并且抛出异常
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新板块中帖子的数量
        boardService.subOneArticleCountById(article.getBoarId());
        //更新用户发布帖子数
        userService.subOneArticleCountById(article.getUserId());
    }

    @Override
    public void addOneReplyCountById(Long id) {
        //参数的非空校验
        if(id==null||id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article=articleMapper.selectByPrimaryKey(id);
        //判断ID代表的目标帖子是否存在
        if(article==null||article.getDeleteState()==1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 帖子已封帖
        if (article.getState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        Article updateArticle=new Article();
        updateArticle.setReplyCount(article.getReplyCount()+1);
        updateArticle.setId(id);
        updateArticle.setUpdateTime(new Date());
        //更新数据库
        int row=articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            //更新失败打印日志并且抛出异常
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        //非空校验
        if(userId==null||userId<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验用户是否存在
        User user = userService.selectById(userId);
        if (user == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", user id = " + userId);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //调用DAO
        List<Article>articles=articleMapper.selectByUserId(userId);
        return articles;
    }
}
